package com.itheima.health.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.dto.SetmealDTO;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.SetmealMapper;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.RedisSetmeal;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.aliyunoss.AliyunUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisConstant;
import com.itheima.health.vo.CheckGroupVO;
import com.itheima.health.vo.SetmealVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Boolean saveSetmeal(SetmealDTO setmealDTO) {

        boolean flag = saveOrUpdate(setmealDTO);
        Integer id = setmealDTO.getId();
        //  中间表 t_setmeal_checkgroup  录入数据
        Integer[] checkgroupIds = setmealDTO.getCheckgroupIds();
        for (Integer checkgroupId : checkgroupIds) {
            baseMapper.addSetmealAndGroupInfo(id, checkgroupId);
        }
        //  set  集合 移除    图片信息   ---set   存放垃圾图片
        RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET, setmealDTO.getImg());
        return flag;  //
    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //  条件构造出来   Wrapper对象
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<Setmeal>();
        Page<Setmeal> page = null;
        if (StringUtils.isBlank(queryPageBean.getQueryString())) {
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()));
        } else {
            queryWrapper.like("HELPCODE", queryPageBean.getQueryString());
            //   sql   + 追加  sql  where  name like  %?%
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()), queryWrapper);
        }
        PageResult result = new PageResult(page.getTotal(), page.getRecords());
        return result;
    }

    /**
     * 该方法： xxl-job 框架调用
     */
    @Override
    public void clearOssImg() {
        //    清理  oss  垃圾图片   该方法 有  xxl-job 去调用
        //  1.  获取 set 集合 所有图片信息
        Set<String> members = RedisUtil.getMembersOfSet(RedisConstant.ALL_SETMEAL_PIC_SET);
        if (members.size() != 0) {
            for (String uuidfilename : members) {
                //   遍历 图片  判断 redis 该图片有没有存在
                boolean existsKey = RedisUtil.existsKey(RedisConstant.SINGLE_PIC + uuidfilename);
                if (existsKey == false) {
                    //   set集合中没找到  redis 对应得图片信息  那么通知 oss删除图片即可
                    AliyunUtils.deleteFile(uuidfilename);
                    System.out.println("-----阿里云删除垃圾图片一次----");
                    //  set    集合  垃圾图片 删除
                    RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET, uuidfilename);
                }
            }
        }

    }

    @Override
    public SetmealVO findSetMealDetail(int id) {
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //  3条 sql
        //  1.  根据套餐id  查询 套餐
   /*     SetmealVO setmealVO = baseMapper.findSetmealById(id);
        // 2  根据 套餐id  查询对应检查组
        List<CheckGroupVO>  checkGroupVOList = baseMapper.findCheckGroupInfosBySetmealId(id);
        // 3  根据检查组id  查询 检查项信息
        for (CheckGroupVO checkGroupVO : checkGroupVOList) {
             List<CheckItem> checkItemList =  baseMapper.findCheckItemsByCheckGroupId(checkGroupVO.getId());
             checkGroupVO.setCheckItemList(checkItemList);
        }
        setmealVO.setCheckGroupList(checkGroupVOList);
        return setmealVO;*/


        //缓存中通过id获得key
        Object redisSetMealDetail = redisTemplate.boundValueOps(id + RedisSetmeal.SETMEALMESSAGE_LOGIN).get();
        //强转为String再转回来
        String s = String.valueOf(redisSetMealDetail);
        System.out.println("====================================================");
        //json字符串转换为对象
        SetmealVO setmealVO = JSON.parseObject(s, SetmealVO.class);

        if (setmealVO != null) {
            System.out.println("从缓存中根据id读取套餐详细信息");
            return setmealVO;

        } else {
            System.out.println("id读取套餐详细信息");
            //   1 查询 套餐基本信息多表查询
            setmealVO = baseMapper.findSetmealById(id);
            //   2 查询 根据套餐id得到检查组信息
            List<CheckGroupVO> checkGroupVOList = baseMapper.findCheckGroupInfosBySetmealId(id);
            //  3 根据检查组信息得到对应检查项信息 循环遍历
            for (CheckGroupVO checkGroupVO : checkGroupVOList) {
                List<CheckItem> checkItemList = baseMapper.findCheckItemsByCheckGroupId(checkGroupVO.getId());
                checkGroupVO.setCheckItemList(checkItemList);
            }
            setmealVO.setCheckGroupList(checkGroupVOList);
            //对象先转换为json字符串
            String abc = JSON.toJSONString(setmealVO);
            //放入缓存每个套餐 id对应一个缓存key的唯一标识  比如1 SETMEALMSG
            redisTemplate.boundValueOps(id + RedisSetmeal.SETMEALMESSAGE_LOGIN).set(abc);
            return setmealVO;

        }

   /* @Override
    public List<Setmeal> findAllSetmeal() {
            //判断缓存中是否有数据
            Object redisSetmeal = redisTemplate.boundValueOps(RedisSetmeal.SETMEAL).get();

            if (redisSetmeal != null) {
                System.out.println("从缓存中读取套餐菜单列表");
                List<Setmeal> list = (List<Setmeal>) redisTemplate.boundValueOps(RedisSetmeal.SETMEAL).get();
                return list;
            }

            System.out.println("从数据库中查询套餐列表");
            redisTemplate.boundValueOps(RedisSetmeal.SETMEAL).set(baseMapper.selectList(null));
            return baseMapper.selectList(null);
    }*/


    }

    @Override
    public List<Setmeal> findAllSetmeal() {
        //判断缓存中是否有数据
        Object redisSetmeal = redisTemplate.boundValueOps(RedisSetmeal.SETMEAL).get();

        if (redisSetmeal != null) {
            System.out.println("从缓存中读取套餐菜单列表");
            List<Setmeal> list = (List<Setmeal>) redisTemplate.boundValueOps(RedisSetmeal.SETMEAL).get();
            return list;
        }

        System.out.println("从数据库中查询套餐列表");
        redisTemplate.boundValueOps(RedisSetmeal.SETMEAL).set(baseMapper.selectList(null));
        return baseMapper.selectList(null);
    }

    @Override
    public SetmealVO findSetmealById(Integer id) {
        return baseMapper.findSetmealById(id);
    }
}
